package com.sirui.x.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 参照 org.springframework.util.StreamUtils
 * 这里不引用其他jar包，copy过来，生产中可以优先使用 spring自带的util或者apache的，亦或者hutool的
 */
public class StreamUtils {

	public static final int BUFFER_SIZE = 4096;
	
	public static byte[] copyToByteArrayMax4096(InputStream in) throws IOException {
		if (in == null) {
			return new byte[0];
		}

		ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
		copyMax4096(in, out);
		return out.toByteArray();
	}
	
	public static int copyMax4096(InputStream in, OutputStream out) throws IOException {

		int byteCount = 0;
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		if((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
			byteCount += bytesRead;
		}
		out.flush();
		return byteCount;
	}

}
